package org.apple.core;

import java.util.Vector;
import java.util.Properties;

import org.apple.messagegenerate.MessageGenerator;
import org.apple.sensor.monitor.SensorMonitor;
import org.apple.util.Configure;

public class Controller {
	
	private Vector<SensorMonitor> sensorMonitors;
	private MessageGenerator messageGenerator;
	
	public Controller() {
		Properties prop = Configure.instance();
		try {
			this.messageGenerator = (MessageGenerator)Class.forName(
					prop.getProperty("messageGenrator", "org.apple.messagegenerate.DefaultMessageGenrator"))
					.newInstance();
			sensorMonitors = new Vector<SensorMonitor> ();

			if ("true".equals(prop.getProperty("collectAirTemperature"))) {
				sensorMonitors.add(
						(SensorMonitor)Class.forName(
								"org.apple.sensor.monitor.AirTempratureSensorMonitor")
								.newInstance());
				System.out.println("Configure: [Controller -> sensorMonitors]"
						+ " org.apple.sensor.monitor.AirTempratureSensorMonitor");
			}
			if ("true".equals(prop.getProperty("collectSeaTemperature"))) {
				sensorMonitors.add(
						(SensorMonitor)Class.forName(
								"org.apple.sensor.monitor.SeaTempratureSensorMonitor")
								.newInstance());
				System.out.println("Configure: [Controller -> sensorMonitors]"
						+ " org.apple.sensor.monitor.SeaTempratureSensorMonitor");
			}
			if ("true".equals(prop.getProperty("collectWindSpeed"))) {
				sensorMonitors.add(
						(SensorMonitor)Class.forName(
								"org.apple.sensor.monitor.WindSpeedSensorMonitor")
								.newInstance());
				System.out.println("Configure: [Controller -> sensorMonitors]"
						+ " org.apple.sensor.monitor.WindSpeedSensorMonitor");
			}
			
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	public void init() {
		for (int i = 0; i < sensorMonitors.size(); i ++) {
			sensorMonitors.get(i).init();
		}
		messageGenerator.init();
	}
	
	public void start() {
		for (int i = 0; i < sensorMonitors.size(); i ++) {
			sensorMonitors.get(i).startMonitor();
		}
		messageGenerator.startGenerator();
	}
	
	public static void main(String[] args) {
		Controller controller = new Controller();
		controller.init();
		controller.start();
	}
}
